/**
 * 
 */
package de.mbenning.fsim.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * @author Martin.Benning
 *
 */
public class ServletRequestHelper {
	
	public static String uploadFile(HttpServletRequest request, String requestFileParam) throws IOException {
		if (!MultipartHttpServletRequest.class.isInstance(request)) {
            return null;
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile(requestFileParam);
        if ((multipartFile == null)
                || multipartFile.isEmpty()) {
            return null;
        }
    	InputStream in = multipartFile.getInputStream();
    	String filename = multipartFile.getFileItem().getName();
    	String outputDir = ResourceBundle.getBundle("fsim-webeditor").getString("fsim.webeditor.uploaddir");
    	writeUploadedFile(in, outputDir + "/" + filename);
    	return filename;
	}
	
	public static void writeUploadedFile(InputStream in, String targetPath) throws IOException {
		File file = new File(targetPath);
		FileOutputStream fos = new FileOutputStream(file);
		
		byte  buffer[] = new byte[0xffff];
		int   nbytes;

	    while ( (nbytes = in.read(buffer)) != (-1) ) {
	        fos.write(buffer, 0, nbytes );
	    }
	    
	    if(in != null) {
	    	in.close();
	    }
	    if(fos != null) {
	    	fos.close();
	    }
	}

}
